﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Oplaco.Web.DTO;
using Oplaco.Core.BusinessLogicLayer;
using System.Configuration;
using Oplaco.Web.UI;
using Oplaco.Core.Configuration;
using System.IO;

public partial class Controls_ShowAddControl : System.Web.UI.UserControl
{
    public String CssClass
    {
        set;
        get;
    }



    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            try
            {
                int adId;
                string adIdQs = Request.QueryString["id"];
                if (adIdQs != null && !Int32.TryParse(adIdQs, out adId))
                {
                    Response.Redirect("~/Search.aspx");
                }

                CachedAdvertisment ad = AdvertismentManager.FetchSingle(HttpContext.Current, Int32.Parse(adIdQs));
                CachedCategory cat = CategoryManager.FetchSingle(ad.CategoryId);
                
                AdType adtype = (AdType)Enum.Parse(typeof(AdType), ad.AdvertismentType, false);

                if (cat.ParentId == 0) CategoryDropDownList1.SelectedCategoryId = cat.Id;
                else
                {                    
                    CategoryDropDownList1.SelectedCategoryId = cat.ParentId;
                    CategoryDropDownList1.SelectedChildCategoryId = cat.Id;
                }
                txtTitle.Text = ad.Title;
                txtDescription.Text = ad.Description;
                txtPrice.Text = ad.Price.ToString();

                ListItemCollection adtypes = new ListItemCollection();
                int integerValueForSale = (int)AdType.ForSale;
                int integerValueWanted = (int)AdType.Wanted;
                ListItem forsaleItem = new ListItem(String.Format(new AdTypeFormatProvider(), "{0}", AdType.ForSale), integerValueForSale.ToString());
                forsaleItem.Selected = true;
                ListItem wantedItem = new ListItem(String.Format(new AdTypeFormatProvider(), "{0}", AdType.Wanted), integerValueWanted.ToString());

                adtypes.Add(forsaleItem);
                adtypes.Add(wantedItem);

                ddlAdTypes.DataSource = adtypes;
                ddlAdTypes.SelectedValue = adtype.ToString();
                ddlAdTypes.DataBind();

                txtUrl.Text = Server.HtmlDecode(ad.Url);


                RepeaterImages.DataSource = ImageManager.FetchImageIdentifiers(HttpContext.Current, ad.Id);
                RepeaterImages.DataBind();

                ViewState["aId"] = ad.Id;


            }
            catch (Oplaco.Exceptions.BusinessLayerException BLE)
            {
                lblMessage.Text = ConfigurationManager.AppSettings["GenericErrorMessage"];
                lblMessage.Visible = true;
                lblMessage.CssClass = "error";
            }
            catch (Exception exception)
            {                
                lblMessage.Text = ConfigurationManager.AppSettings["GenericErrorMessage"];
                lblMessage.Visible = true;
                lblMessage.CssClass = "error";
                Oplaco.Exceptions.AppService.ProcessAndNotifyPresentationLayerException(exception);
            }
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {

        if (Page.IsValid)
        {
            try
            {
                SiteSettings s = SiteSettings.GetSharedSettings();
                int zipcode = 0;
                int subCategoryId = 0;
                string zipcodeExtension = String.Empty;
                object ozip = Profile.GetPropertyValue("Zipcode");
                object ozipex = Profile.GetPropertyValue("ZipcodeExtension");
                int adId = Int32.Parse(ViewState["aId"].ToString());

                int memberId = 0;
                if (Page.User.Identity.IsAuthenticated)
                {
                    if (!Page.User.IsInRole("Users")) throw new Oplaco.Exceptions.PresentationLayerException("Only users in role 'Users' are allowed to post an ad");
                    UserDefinedProfile profile = new UserDefinedProfile();
                    memberId = Profile.MemberId; //(Int32)profile.GetPropertyValue("MemberId");
                }
                else
                {

                    Oplaco.Exceptions.AppService.ProcessAndNotifyPresentationLayerException(new Exception("No valid member to process the request")); //make sure admin or not logged in user processes order
                }

                if (ozip != null) zipcode = Convert.ToInt32(ozip);
                if (ozipex != null) zipcodeExtension = (String)ozipex;

                //process categories
                DropDownList ddlCategories = (DropDownList)CategoryDropDownList1.FindControl("ddlCategories");
                DropDownList ddlSubCategories = (DropDownList)CategoryDropDownList1.FindControl("ddlSubCategories");

                if (!String.IsNullOrEmpty(ddlSubCategories.SelectedValue)) subCategoryId = Int32.Parse(ddlSubCategories.SelectedValue);
                int categoryId = Int32.Parse(ddlCategories.SelectedValue);
                if (subCategoryId > 0) categoryId = subCategoryId;

                //process other order values
                string title = Server.HtmlEncode(txtTitle.Text);
                string description = Server.HtmlEncode(txtDescription.Text);
                string url = txtUrl.Text;
                Decimal price = Decimal.Parse(txtPrice.Text);

                //get location if provided, if not, we use the location from the user.
                string location = Profile.ZipCode + Profile.ZipCodeExtension;


                //we do not show numDays in the GUI, if you want to use this, just add a dropdownlist to the page and get the value of that dropdown
                //for example : int numDays = Convert.ToInt32(ddlNumberOfDays.SelectedValue);
                int numDays = Convert.ToInt32(s.MaxAdRunningDays);

                //process ad type
                AdType adType = AdType.ForSale;
                if (Enum.IsDefined(typeof(AdType), ddlAdTypes.SelectedValue)) adType = (AdType)Enum.Parse(typeof(AdType), ddlAdTypes.SelectedValue);

                //process order
                AdsDB.UpdateAd(adId, memberId, title, description, url, price, location, false);


                //now the photos                
                this.handlePhotoUpload(FileUpload1, adId);
                this.handlePhotoUpload(FileUpload2, adId);
                this.handlePhotoUpload(FileUpload3, adId);


                Response.Redirect("~/MyShop/MyAds.aspx");
            }
            catch (Oplaco.Exceptions.BusinessLayerException BLE)
            {
                lblMessage.Text = BLE.Message;
            }
            catch (Oplaco.Exceptions.PresentationLayerException PLE)
            {
                lblMessage.Text = PLE.Message;
            }
            catch (Exception ex)
            {
                Oplaco.Exceptions.AppService.ProcessAndNotifyPresentationLayerException(ex);
                lblMessage.Text = ex.Message;
            }
        }

    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {

        if (Page.IsValid)
        {
            try
            {
                int adId = Int32.Parse(ViewState["aId"].ToString());
                string url = "~/MyShop/MyAds.aspx";
                int memberId = 0;
                if (Page.User.Identity.IsAuthenticated)
                {
                    UserDefinedProfile profile = new UserDefinedProfile();
                    memberId = Profile.MemberId; //(Int32)profile.GetPropertyValue("MemberId");
                    if(Page.User.IsInRole("Admin")) url = "~/Admin/Default.aspx";
                }
                else
                {

                    Oplaco.Exceptions.AppService.ProcessAndNotifyPresentationLayerException(new Exception("No valid member to process the request")); //make sure admin or not logged in user processes order
                }

                AdsDB.RemoveFromDatabase(adId);
                Response.Redirect(url);
            }
            catch (Oplaco.Exceptions.BusinessLayerException BLE)
            {
                lblMessage.Text = BLE.Message;
            }
            catch (Oplaco.Exceptions.PresentationLayerException PLE)
            {
                lblMessage.Text = PLE.Message;
            }
            catch (Exception ex)
            {
                Oplaco.Exceptions.AppService.ProcessAndNotifyPresentationLayerException(ex);
                lblMessage.Text = ex.Message;
            }
        }
    }

    private void handlePhotoUpload(FileUpload uploadcontrol, int adId)
    {

        SiteSettings settings = SiteSettings.GetSharedSettings();
        // Specify the path on the server to
        // save the uploaded file to.
        string savePath = settings.ServerPhotoUploadDirectory;

        try
        {



            // Before attempting to save the file, verify
            // that the FileUpload control contains a file.
            if (uploadcontrol.HasFile)
            {
                // Get the name of the file to upload.
                string fileName = Server.HtmlEncode(uploadcontrol.FileName);

                // Get the extension of the uploaded file.
                string extension = System.IO.Path.GetExtension(fileName);

                // Allow only files with .doc or .xls extensions
                // to be uploaded.

                if (Array.IndexOf(settings.AllowedImageTypes, extension) >= 0)
                {
                    // Append the name of the file to upload to the path.
                    savePath = "/" + savePath + "/" + fileName;

                    // Call the SaveAs method to save the 
                    // uploaded file to the specified path.
                    // This example does not perform all
                    // the necessary error checking.               
                    // If a file with the same name
                    // already exists in the specified path,  
                    // the uploaded file overwrites it.
                    uploadcontrol.SaveAs(HttpContext.Current.Server.MapPath("~" + savePath));
                    byte[] rawData = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~" + savePath));
                    PhotosDB.InsertPhoto(adId, rawData, PhotosDB.ResizeImageFile(rawData, PhotoSize.Medium), PhotosDB.ResizeImageFile(rawData, PhotoSize.Small), true);
                }
                else
                {
                    // Notify the user why their file was not uploaded.
                    string message = "Your ad had been created, but your photo was not uploaded because it does not have a .png, .gif or .jpg extension.<br/> You can add your photo in your shop section";
                    Oplaco.Exceptions.AppService.ProcessAndNotifyPresentationLayerException(new Exception(message));
                }

            }
        }
        catch (Exception exception)
        {
            Oplaco.Exceptions.AppService.ProcessAndNotifyPresentationLayerException(exception);
        }

    }
}